#!/bin/bash

set -e

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

function download_codes(){
  echo "# 正在下载bwa与相关文件"
  wget -t 40 -c -P $1 https://github.com/lh3/bwa/archive/refs/tags/0.7.10.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# bwa克隆成功\033[0m"
  else
    echo -e "\033[31m# bwa克隆失败,请重新执行脚本\033[0m"
    exit 1
  fi
  wget -t 40 -c -P $1 https://github.com/DLTcollab/sse2neon/archive/refs/tags/v1.5.1.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# 依赖文件库sse2neon下载成功\033[0m"
  else
    echo -e "\033[31m# 依赖文件库sse2neon克隆失败,请重新执行脚本\033[0m"
    exit 1
  fi
  tar xf $1/0.7.10.tar.gz -C $1
  tar xf $1/v1.5.1.tar.gz -C $1
  mv $1/bwa-0.7.10 $1/bwa
  cd "$1"/bwa
  mv ../sse2neon-1.5.1/sse2neon.h sse2neon.h
  rm -rf "$1"/sse2neon-1.5.1
}

function install_bwa(){
  cd "$1"/bwa
  sed -i 's/<emmintrin.h>/"sse2neon.h"/g' ksw.c
  make -j $(nproc) CC=clang
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# bwa已经安装成功\033[0m"
  else
    echo -e "\033[31m# bwa安装失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function cp_bwa(){
  mkdir -p "$2"/bwa-0.7.10
  cp -r "$1"/bwa/* "$2"/bwa-0.7.10
}

function write_bwa_module() {
  cat >"$1/bwa-0.7.10/bwa_modulefiles"<<EOF
#%Module1.0
conflict bwa
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
prepend-path PATH \$pwd
EOF
}


function main() {
  is_equal_build_install_path "$1" "$2"
  download_codes "$1"
  install_bwa "$1" "$2"
  cp_bwa "$1" "$2"
  write_bwa_module "$2"
  rm -rf "$1"/bwa
}

main "$@"